package com.qf.web;

import com.alibaba.fastjson.JSON;
import com.qf.common.R;
import com.qf.pojo.Student;
import com.qf.service.StudentService;
import com.qf.service.impl.StudentServiceImpl;
import com.qf.utils.DateUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @date 2022/4/2
 * @desc
 */
@WebServlet("/addStudent")
public class AddStudentServlet  extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 接受表单数据
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String hobby = req.getParameter("hobby");

        // 封装数据到对象
        //字符串转日期
        Date date = DateUtil.strToDate(birthday, "yyyy-MM-dd");
        //封装到对象中
        Student student = new Student(name, sex, date, phone, address, hobby);

        StudentService studentService = new StudentServiceImpl();
        // 调用service 的添加方法
        int result = studentService.addStudent(student);

        if(result==1){
            // 添加成功
            R ok = R.ok();
            String s = JSON.toJSONString(ok);
            resp.getWriter().println(s);
        }else{
            // 添加失败
            R error = R.error();
            String s = JSON.toJSONString(error);
            resp.getWriter().println(s);

        }

    }
}
